<?php


/**
 * 前提条件：
 * 去控制台中，给live表创建一个二级索引。
 * 名字叫：status-count-index
 * 分区键是：status
 * 排序键是：count
 */
require '../vendor/autoload.php';

use Aws\DynamoDb\Exception\DynamoDbException;
use Aws\DynamoDb\Marshaler;
$sdk = new Aws\Sdk([
    'region'   => 'us-west-2',
    'version'  => 'latest',
    'credentials' => [
        'key' => 'AKIA4SBKFCJAXUOUXUN2',
        'secret' => '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',
    ],
]);

$dynamodb = $sdk->createDynamoDb();
$marshaler = new Marshaler();
$tableName = 'live';
$eav = $marshaler->marshalItem([':value'=>'living']);//必须和KeyConditionExpression中定义的 :value一致
$params = [
    'TableName' => $tableName,
    "IndexName" =>'status-count-index',
    'KeyConditionExpression' => '#fieldname = :value',// #fieldname 和 :value 都可以任意取名
    'ExpressionAttributeNames'=> [ '#fieldname' => 'status' ],//绑定属性名，
    'ExpressionAttributeValues'=> $eav , //绑定属性值,
    'ScanIndexForward'=>false, //按sortkey 倒序排列
];

try {
    $result = $dynamodb->query($params);
    echo "Query succeeded.\n";
    foreach ($result['Items'] as $v) {
        var_dump($marshaler->unmarshalItem($v));
    }

} catch (DynamoDbException $e) {
    echo "Unable to query:\n";
    echo $e->getMessage() . "\n";
}